package jhc.cn.moviegallery;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by luyanfei on 16-11-23.
 */

public class ThumbnailDownloader<T> extends HandlerThread {
    private static final String TAG = "ThumbnailDownloader";
    private static final int MESSAGE_DOWNLOAD = 0;

    private Handler requestHandler;
    private Handler responseHandler;
    private ConcurrentHashMap<T, String> requestMap = new ConcurrentHashMap<>();
    private ThumbnailDownloaderListener listener;

    public interface ThumbnailDownloaderListener<T> {
        void onThumbnailDownloaded(T target, Bitmap thumbnail);
    }

    public ThumbnailDownloader(Handler respHandler) {
        super(TAG);
        this.responseHandler = respHandler;
    }

    public void setListener(ThumbnailDownloaderListener listener) {
        this.listener = listener;
    }

    public void queueThumbnail(T target, String url) {
        Log.i(TAG, "Got a URL: " + url);

        if(url == null) {
            requestMap.remove(target);
        } else {
            requestMap.put(target, url);
            requestHandler.obtainMessage(MESSAGE_DOWNLOAD, target).sendToTarget();
        }
    }

    public void clearQueue() {
        requestHandler.removeMessages(MESSAGE_DOWNLOAD);
    }

    @Override
    protected void onLooperPrepared() {
        requestHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == MESSAGE_DOWNLOAD) {
                    T target = (T) msg.obj;
                    Log.i(TAG, "Got a request for url: " + requestMap.get(target));
                    handleRequest(target);
                }
            }
        };
    }

    private void handleRequest(final T target) {
        try {
            final String url = requestMap.get(target);
            if(url == null) return;
            byte[] bitmapBytes = new DoubanFetchr().getUrlBytes(url);
            final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
            Log.i(TAG, "Bitmap created.");

            responseHandler.post(new Runnable() {
                @Override
                public void run() {
                    //此处的重复检查是必须的，因为RecyclerView可能会重用MovieHolder。
                    //从网络下载图片需要时间，在这个间隙，RecyclerView可能会将MovieHolder对象绑定到另一个URL上。
                    //为保证MovieHolder对象与URL的对应，需要下面这行检查。
                    if(requestMap.get(target) != url) return;
                    requestMap.remove(target);
                    listener.onThumbnailDownloaded(target, bitmap);
                }
            });
        } catch (IOException e) {
            Log.e(TAG, "Error downloading image.", e);
        }
    }
}
